# coding = utf-8

'''
用来分析gabor滤波在单独区域和肿瘤区域的区别
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image
import math
from skimage import measure

def garbor_filter4(image):
    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters3 = []
    #theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi/6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi / 2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        #kern = cv2.getGaborKernel((10, 10), sigma=1.0, theta=item, lambd=5, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    #clahe = cv2.createCLAHE(clipLimit=5, tileGridSize=(100, 100))
    result3 = cv2.equalizeHist(result3)
    #result3 = clahe.apply(result3)

    return result3

def garbor_filter4_v2(image, big_liver):
    image = image * 255
    image = image.astype(np.uint8)

    temp = np.zeros(image.shape)

    filters3 = []
    #theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi / 6]
    theta2 = [0, 1 * np.pi / 6, 2 * np.pi / 6, 3 * np.pi / 6, 4 * np.pi / 6, 5 * np.pi/6]
    for item in theta2:
        kern = cv2.getGaborKernel((2, 2), sigma=1.0, theta=item, lambd=np.pi / 2.0, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        #kern = cv2.getGaborKernel((10, 10), sigma=1.0, theta=item, lambd=5, gamma=0.5, psi=0, ktype=cv2.CV_32F)
        kern /= 1.5 * kern.sum()
        filters3.append(kern)
    result3 = np.zeros_like(temp)
    for i in range(len(filters3)):
        accum = np.zeros_like(image)
        for kern in filters3[i]:
            fimg = cv2.filter2D(image, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        result3 += np.array(accum)
    result3 = result3 / len(filters3)
    result3 = result3.astype(np.uint8)
    result3 = result3 * big_liver
    #clahe = cv2.createCLAHE(clipLimit=5, tileGridSize=(100, 100))
    result3 = cv2.equalizeHist(result3)
    #result3 = clahe.apply(result3)

    return result3

def find_data(case_id, origion_id, index):
    big_image = "E:\Dataset\Liver\qiye\DongBeiDaXue2\image_venous\\data2_{}_venous.mha".format(origion_id)
    big_liver = "E:\Dataset\Liver\qiye\DongBeiDaXue2\liver\\data2_{}_liver_label.mha".format(origion_id)
    big_tumor = "E:\Dataset\Liver\qiye\DongBeiDaXue2\lesion\\data2_{}_lesion_label.mha".format(origion_id)
    big_fusion = "E:\predict\image_tumor\case_{}\\fusion\\{}.png".format(str(case_id).zfill(5), str(index).zfill(3))
    big_image = sitk.GetArrayFromImage(sitk.ReadImage(big_image))
    big_image[big_image <= -200] = -200
    big_image[big_image > 250] = 250
    big_image = (big_image + 200) / 450
    big_image = big_image[index]
    big_liver = sitk.GetArrayFromImage(sitk.ReadImage(big_liver))
    big_liver = big_liver[index]
    big_tumor = sitk.GetArrayFromImage(sitk.ReadImage(big_tumor))
    big_tumor = big_tumor[index]
    big_fusion = Image.open(big_fusion)
    return (big_image, big_fusion, big_liver, big_tumor)


def with_liver():
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=79, origion_id="0865", index=262)


    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    liver = (big_image) * big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    garbor_result = garbor_filter4(big_image * big_liver)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=5)


    data[data <= 200] = 0
    data[data > 200] = 1

    liver_t = np.zeros(data.shape)
    temp = big_image * big_liver
    liver_t += (temp * data)
    liver_t += (temp * (1 - data) * 1.2)
    liver_t = liver_t / 1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)


    plt.subplot(1, 3, 1)
    plt.title("origion image")
    plt.imshow(liver)
    plt.subplot(1, 3, 2)
    plt.title("gabor enhance")
    plt.imshow(image)
    plt.subplot(1, 3, 3)
    plt.title("mask")
    plt.imshow(data, cmap="gray")
    plt.show()

def without_liver():
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id=79, origion_id="0865", index=262)


    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    liver = (big_image) * big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    liver = cv2.equalizeHist(liver)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    garbor_result = garbor_filter4_v2(big_image, big_liver)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=5)


    data[data <= 200] = 0
    data[data > 200] = 1

    liver_t = np.zeros(data.shape)
    temp = big_image * big_liver
    liver_t += (temp * data)
    liver_t += (temp * (1 - data) * 1.2)
    liver_t = liver_t / 1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)


    plt.subplot(1, 3, 1)
    plt.title("origion image")
    plt.imshow(liver)
    plt.subplot(1, 3, 2)
    plt.title("gabor enhance")
    plt.imshow(image)
    plt.subplot(1, 3, 3)
    plt.title("mask")
    plt.imshow(data, cmap="gray")
    plt.show()


def gabor_standard():
    (big_image, big_fusion, big_liver, big_tumor) = find_data(case_id="65", origion_id="0394", index=203)

    big_tumor[big_tumor > 0] = 1
    big_tumor = big_tumor * 255
    big_tumor = big_tumor.astype(np.uint8)
    contours, _ = cv2.findContours(big_tumor, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    liver = (big_image) * big_liver
    liver = liver * 255
    liver = liver.astype(np.uint8)
    liver = cv2.cvtColor(liver, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    print(np.max(big_image*big_liver))
    garbor_result = garbor_filter4(big_image * big_liver)
    image = cv2.cvtColor(garbor_result, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(image, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    data = cv2.medianBlur((255 - garbor_result) * big_liver, ksize=5)

    data[data <= 150] = 0
    data[data > 150] = 1

    liver_t = np.zeros(data.shape)
    temp = big_image * big_liver
    liver_t += (temp * data)
    liver_t += (temp * (1 - data) * 1.2)
    liver_t = liver_t / 1.2
    liver_t = liver_t * 255
    liver_t = liver_t.astype(np.uint8)
    liver_t = cv2.cvtColor(liver_t, cv2.COLOR_GRAY2BGR)
    for counter in contours:
        data_list = []
        for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
        cv2.polylines(liver_t, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)

    plt.subplot(1, 3, 1)
    plt.title("origion image")
    plt.imshow(liver)
    plt.subplot(1, 3, 2)
    plt.title("gabor enhance")
    plt.imshow(image)
    plt.subplot(1, 3, 3)
    plt.title("mask")
    plt.imshow(data, cmap="gray")
    plt.show()


if __name__ == '__main__':
    gabor_standard()